<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>compact和 chunk 实现</title>
</head>

<body>
  <script>
    let arr = [null, undefined, {}, "", 1, 2, 3, -1, 0, true, false]
    /* 
      1. compact(): 返回数组中所有真值组成的数组
     */
    Array.prototype.compact = function () {
      return this.filter(item => item)
    }
    console.log(arr.compact())

    /* 
    2. chunk(size):  将数组拆分多个 size 长度的区块，各个区块组成小数组，整体组成一个二维数组
     */
    let arr1 = [1, 2, 3, 4, 5, 6, 7, 8]
    Array.prototype.chunk = function (size) {
      // 返回的结果
      const arr = []
      // 处理size的边界值
      if (size < 0) {
        return []
      }
      if (size > this.length) {
        return [this]
      }

      let index = 0;
      while (index < this.length) {
        arr.push(this.slice(index, index = size + index))
      }

      return arr;

    }

    console.log(arr1.chunk(8))
  </script>
</body>

</html>